<?php
// this is the ajax chat state sver and retriever
require_once('../../../config.php');

// use isloggedin() instead, due to wantsurl redirection
// require_login();
header("Content-Type: text/plain; charset=UTF-8");
if (!isloggedin())
	exit;

function var_dump_ret($mixed = null) {
  ob_start();
  var_dump($mixed);
  $content = ob_get_contents();
  ob_end_clean();
  return $content;
}

error_log("in saver");
error_log(var_dump_ret($_GET));

function ret($ok, $extra='')
{
	print "{\"ok\": $ok, \"extra\": \"" . $extra . "\" }";
}


$sessinfo = stripslashes(optional_param('sessinfo', PARAM_RAW));
$action = required_param('action');
$sessid = $USER->sesskey;

switch($action)
{
	case 'set':
		error_log("sessinfo = " . $sessinfo);
		// save the string
		$db->debug = false;
		$rs = $db->Execute("SELECT * FROM mdl_presence_data WHERE sessionid=" . $db->qstr($sessid) . ";");
		if (!$rs || $rs->RecordCount() <= 0)
			if ($db->Execute("INSERT INTO mdl_presence_data (sessionid,sessinfo) VALUES ('" .$sessid. "','" . $sessinfo . "');") === false)
				ret(0, '"' . $db->ErrorMsg() . '"');
			else
				ret(1);
		else
			if ($db->Execute("UPDATE mdl_presence_data SET sessinfo='" . $sessinfo . "',sessiont=NOW() WHERE sessionid='" . $sessid . "';") === false)
				ret(0, '"' . $db->ErrorMsg() . '"');
			else
				ret(1);
		break;

	case 'get':
		// return the string
		$db->SetFetchMode(ADODB_FETCH_ASSOC);
		$rs = $db->Execute("SELECT * FROM mdl_presence_data WHERE sessionid=" . $db->qstr($sessid) . " ORDER BY sessiont DESC LIMIT 1;");
		if (!$rs || $rs->RecordCount() <= 0)
			ret(0);
		else
		{
			//XXX: This might be cleaned up, right now it prevents ugly utf-8 stuff slipping through
			//     and being interpreted just as iso-8859-1 ... bleh
			$buf = stripslashes($rs->fields["sessinfo"]);
			/*$buf = rawurldecode(stripslashes($rs->fields["sessinfo"]));
			$buf = utf8_decode($buf);
			$buf = rawurlencode($buf);*/
			ret(1,$buf);
		}
		break;
	 case 'saveconv':
		$conv = stripslashes(optional_param('conv', PARAM_RAW));
		$c = json_decode($conv);
		header("content-disposition: attachment; filename=covcellconv_" . $c[0]->u . ".txt");
		print "Log start " . date('Y-m-d H:i:s T', $c[0]->t) . "\r\n";
		for ($i = 0; $i < count($c); $i++)
		{
			print date("H:i:s", $c[$i]->t) . " " . $c[$i]->u . ": " . $c[$i]->m . "\r\n";
		}
		print "Log end " . date('Y-m-d H:i:s T', $c[count($c)-1]->t) . "\n";
		break;
}
// clean old sessinfo stuff... XXX: time limits?

$db->Execute("DELETE FROM mdl_presence_data WHERE sessiont <= DATE_SUB(NOW(), interval 15 minute)");
?>
